package ru.chezclif.lern.conread;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
import ru.chezclif.lern.conread.parser.PathDataInputProperties;
/**
 * Наполнение хранилища данных из файла .properies
 * @author Vit
 *
 */
public class PropertyParser implements PathDataInputProperties {
	private Properties settings = new Properties();
	private DataBuffer propertyBuffer;
	private boolean furstLine = true;
	private boolean endline = false;
	private String standartLine = "";
	private String endLineString = "";
	@Override
	/**По параметру filePath находится файл, из него получают настройки и сохраняют в объект propertyBuffer
	 *@param filePath полный путь к оперируемому файлу
	 *@param propertyBuffer хранилище данных для заполнения*/
	public void parseFile(String fileName, DataBuffer propertyBuffer) {
		Preconditions.notBlank(fileName);
		Preconditions.notNull(fileName);
		Preconditions.notNull(propertyBuffer);
		this.propertyBuffer = propertyBuffer;
		try {
			File propertyFile = new File(fileName);
			FileInputStream fileStream = new FileInputStream(propertyFile);
			InputStream propertyStream = fileStream;
			settings.load(propertyStream);
			propertyStream.close();
			fileStream.close();
			FileReader readFile = new FileReader(fileName);
			BufferedReader bufferForSearchComments = new BufferedReader(readFile);
			if (!(bufferForSearchComments.ready())) {
				throw new ru.chezclif.lern.conread.exceptions.EmptyFileExeption(fileName);
			}
			while ((standartLine = bufferForSearchComments.readLine()) != null) {
				if (!(standartLine.trim() == "")) {
					if ((furstLine == true) && (standartLine.charAt(0) == '#')) {
						this.propertyBuffer.setHeaderComment(standartLine.substring(1));
					}
					if (furstLine) {
						furstLine = !furstLine;
					}
					endLineString = standartLine;
				}
			}
			endline = true;
			if (!(endLineString.trim() == "")) {
				if ((endline == true) && (endLineString.charAt(0) == '#')) {
					this.propertyBuffer.setFooterComment(endLineString.substring(1));
				}
			}
			bufferForSearchComments.close();
		} catch (FileNotFoundException e) {
			throw new ru.chezclif.lern.conread.exceptions.FileNotFoundException(e, fileName);
		} catch (IOException e) {
			throw new ru.chezclif.lern.conread.exceptions.FileNotFoundException(e, fileName);
		}
		Enumeration propertyNameList = settings.keys();
		String key = "";
		String value = "";
		for (Enumeration e = propertyNameList; e.hasMoreElements();) {
			key = (String) e.nextElement();
			value = settings.getProperty(key);
			this.propertyBuffer.setSetting(key, value);
		}
	}
}
